﻿
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

while (true)
{
    string obj=Console.ReadLine();
    AppSendHelper.Push("a879e9ad46de88d353bb5151319d65a2", "title",obj);
}


public static class AppSendHelper
{
    /// <summary>
    /// 
    /// </summary>
    private static string appSendToken = "";

    private static string AppID = "mUenwa2TYjAOXHrwtWsX9A"; 
    private static string AppKey = "LXZrxPfk60Auu1IK4L77v2";
    private static string AppSecret = "zNvnlL56sN6S4hzN8PR4I2";
    private static string MasterSecret = "TfIDU9vCJo8yjoqsFLP8k2";


    /// <summary>
    /// 获取token
    /// </summary>
    /// <returns></returns>
    public static string GetAppSendToken()
    {
        string token = "";
        if (!string.IsNullOrWhiteSpace(appSendToken))
        {
            return appSendToken;
        }

        //签名 ： appkey+timestamp+mastersecret   SHA256加密
        string timestamp = GenerateTimeStamp();//时间戳
        string sign = AppKey + timestamp + MasterSecret;
        sign = sha256(sign); //sha256加密

        var postdata = new
        {
            sign = sign,
            timestamp = timestamp,
            appkey = AppKey
        };
        string data = JsonSerializer.Serialize(postdata);

        WebClient wc = new WebClient();
        string url = $@"https://restapi.getui.com/v2/{AppID}/auth";
        wc.Encoding = Encoding.UTF8;
        wc.Headers.Add("Content-Type", "application/json");
        // wc2.Headers.Add("token", "STZN202204020911111");
        try
        {
            string result = wc.UploadString(url, data);
            //{"msg":"success","code":0,"data":{"expire_time":"1652341431131","token":"ef9b1b20798956299552a28ef549e859f2856eae17a2021c81f85e5e8244a40b"}}
            // string result = "{\"msg\":\"success\",\"code\":0,\"data\":{\"expire_time\":\"1652341431131\",\"token\":\"ef9b1b20798956299552a28ef549e859f2856eae17a2021c81f85e5e8244a40b\"}}";
            var detail = JsonSerializer.Deserialize<AppResultModel>(result);
            appSendToken = detail.data.token;
            token = appSendToken;
        }
        catch (Exception ex)
        {
            throw;
        }

        return token;

    }

    /// <summary>
    /// 推送
    /// </summary>
    public static void Push(string cid, string title,string message)
    {
        string token = GetAppSendToken();
        string guid = Guid.NewGuid().ToString();
        #region 示例说明

        //https://restapi.getui.com/v2/kylXOUvnEd8Al3yT39ELR1/push/single/cid

        //{
        //    "request_id":"xxx",
        //    "settings":{
        //                    "ttl":3600000
        //    },
        //    "audience":{
        //                    "cid":[
        //                        "xxx"
        //        ]
        //    },
        //    "push_message":{
        //        "notification":{
        //            "title":"请填写通知标题",
        //            "body":"请填写通知内容",
        //            "click_type":"url",
        //            "url":"https//:xxx"
        //        }
        //    }
        //}
        #endregion

        APPSendModel postDate = new APPSendModel();
        postDate.request_id = guid;
        postDate.settings.ttl = -1;
        //cid = "323a0a1f8edc92d2ee49cb3c4f19be52";
        postDate.audience.cid.Add(cid);//cid 就是手机的唯一ID，我现在要给这个手机推消息
        postDate.push_message.notification.title = title;
        postDate.push_message.notification.body = message;
        postDate.push_message.notification.click_type = "url";
        postDate.push_message.notification.url = "https//:xxx";
        string data = JsonSerializer.Serialize(postDate);


        WebClient wc = new WebClient();
        string url = $@"https://restapi.getui.com/v2/{AppID}/push/single/cid";
        wc.Encoding = Encoding.UTF8;
        wc.Headers.Add("Content-Type", "application/json");
        wc.Headers.Add("token", token);


        try
        {
            string result = wc.UploadString(url, data);
            var detail = JsonSerializer.Deserialize<AppResultModel>(result);

            //这里就调用成功了，成功的结果是：
            //{
            //    "msg": "success",
            // "code": 0,
            // "data": {
            //        "RASS_0511_713a878aa7e416e0c75c1e43653f7e05": {
            //            "5383f6510d55073580088eb0f857bb17": "successed_offline"


            //        }
            //    }
            //}
        }
        catch (Exception ex)
        {
            throw;
        }

    }


    /// <summary>
    /// 获取时间撮
    /// </summary>
    /// <returns></returns>
    private static string GenerateTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalMilliseconds).ToString();
    }

    /// <summary>
    /// 加密算法
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    private static string sha256(string data)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(data);
        SHA256 sha256has= SHA256.Create();
        byte[] hash = sha256has.ComputeHash(bytes);

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            builder.Append(hash[i].ToString("X2"));
        }
        return builder.ToString();
    }

}


/// <summary>
/// APP 发送 model
/// </summary>
public class AppResultModel
{

    /// <summary>
    /// 
    /// </summary>
    public string msg { get; set; }

    /// <summary>
    /// 10001 就是过期    0 是成功
    /// </summary>
    public int? code { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public AppResultModelDetail data { get; set; }
}

/// <summary>
/// 
/// </summary>
public class AppResultModelDetail
{
    /// <summary>
    /// 
    /// </summary>
    public string expire_time { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public string token { get; set; }
}

/// <summary>
/// app发送model
/// </summary>
public class APPSendModel
{
    public APPSendModel()
    {
        settings = new settings();
        audience = new audience();
        push_message = new push_message();
    }

    /// <summary>
    /// 	请求唯一标识号，10-32位之间；如果request_id重复，会导致消息丢失
    /// </summary>
    public string request_id { get; set; }

    /// <summary>
    /// 推送条件设置，详细解释见下方settings说明
    /// </summary>
    public settings settings { get; set; }

    /// <summary>
    /// 个推推送消息参数，详细内容见push_message
    /// </summary>
    public audience audience { get; set; }

    /// <summary>
    /// 个推推送消息参数
    /// </summary>
    public push_message push_message { get; set; }

}

/// <summary>
/// 推送条件设置
/// </summary>
public class settings
{
    /// <summary>
    /// 	消息离线时间设置，单位毫秒，-1表示不设离线，-1 ～ 3 * 24 * 3600 * 1000(3天)之间
    /// </summary>
    public int? ttl { get; set; }
}

/// <summary>
/// 推送目标用户
/// </summary>
public class audience
{
    /// <summary>
    /// 构造
    /// </summary>
    public audience()
    {
        cid = new List<string>();
    }

    /// <summary>
    /// 别名数组，只能填一个别名；绑定别名请参考
    /// </summary>
    public List<string> cid { get; set; }
}

/// <summary>
/// 发送消息
/// </summary>
public class push_message
{
    /// <summary>
    /// 构造
    /// </summary>
    public push_message()
    {
        notification = new notification();
    }
    /// <summary>
    /// 通知
    /// </summary>
    public notification notification { get; set; }
}

/// <summary>
/// 通知
/// </summary>
public class notification
{
    /// <summary>
    /// 通知标题
    /// </summary>
    public string title { get; set; }

    /// <summary>
    /// 通知内容
    /// </summary>
    public string body { get; set; }

    /// <summary>
    /// 写死 url就好
    /// </summary>
    public string click_type { get; set; }

    /// <summary>
    /// "https//:xxx
    /// </summary>
    public string url { get; set; }
}